<!--
 * @Description: 
 * @Author: 胡涛
 * @Date: 2023-10-24 09:06:08
 * @LastEditors: 胡涛
 * @LastEditTime: 2023-11-22 22:00:31
-->
<template>
  <a-tree-select
    :treeData="regionTreeItems"
    :value="value"
    @change="onValueChanged"
    v-bind="$props"
    :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
    placeholder="请选择区域信息"
    tree-data-simple-mode
    :load-data="onLoadData"
  >
  </a-tree-select>
</template>

<script lang="ts" setup>
import { computed, onMounted, reactive, ref } from "vue";
import { useDataStore } from "@/store";
import { storeToRefs } from "pinia";
import { RegionDto, RegionTreeDto } from "@/api/system/types";
import { data } from "dom7";
import { TreeNodeProps } from "ant-design-vue/es/vc-tree-select/TreeNode";

const dataStore = useDataStore();
const emits = defineEmits(["update:value", "update:name", "change"]);

const props = defineProps({
  value: { type: [String] },
  name: { type: [String] },
});

const regionTreeItems = ref<Array<any>>([]);

const onLoadData = (treeNode: TreeNodeProps["treeData"][number]) => {
  return new Promise((resolve) => {
    const { id } = treeNode.dataRef;
    setTimeout(() => {
      regionTreeItems.value = regionTreeItems.value.concat(
        createChildrenItems(id)
      );
      resolve(true);
    }, 0);
  });
};

/**
 *
 * @param allItems
 * @param parentId
 */
const createChildrenItems = (parentId?: string) => {
  let items: Array<RegionDto> = [];
  const { regionItems } = dataStore;
  if (!parentId) {
    items = regionItems.filter((x) => !x.parentId);
  } else {
    items = regionItems.filter((x) => x.parentId == parentId);
  }
  return items.map((x) => {
    let item: any = {
      id: x.id,
      pId: parentId,
      value: x.id,
      title: x.name,
      ...x,
    };
    if (regionItems.filter((c) => c.parentId == x.id).length === 0) {
      item.isLeaf = true;
    }
    return item;
  });
};

const onValueChanged = (value: string) => {
  let name = dataStore.regionItems.find((x) => x.id == value)?.name;
  emits("update:value", value);
  emits("update:name", name);
  emits("change", value);
};

onMounted(async () => {
  regionTreeItems.value = createChildrenItems();
});
</script>

<style lang="less" scoped></style>
